{% extends 'base.html' %}

{% block page-container %}
<div class="chat-container">
    <div class="left-contact-panel">
        contacts
        <div>

          <!-- Nav tabs -->
          <ul class="nav nav-tabs" role="tablist">
            <li role="presentation" class="active">
                <a href="#contact-tab"  role="tab" data-toggle="tab">好友</a>
            </li>
            <li role="presentation">
                <a href="#group-tab"  role="tab" data-toggle="tab">群组</a>
            </li>
          </ul>

          <!-- Tab panes -->
          <div class="tab-content">
            <div role="tabpanel" class="tab-pane active" id="contact-tab">
               <ul class="list-group">
                {% for friend in request.user.userprofile.friends.select_related %}
                    <li contact-type="single" contact-id="{{ friend.id }}" onclick="OpenChatWindow(this)" class="list-group-item">
                        <span class="badge hide"></span>
                        <span class="contact-name"> {{ friend.name }} </span>
                    </li>
                {% endfor %}
            </ul>

            </div>
            <div role="tabpanel" class="tab-pane" id="group-tab">
                gropu
            </div>

          </div>

        </div>



    </div>
    <div class="right-chat-panel">
        <div class="chat-box-title" contact-type="" contact-id="">
            title
        </div>
        <div class="chat-box-window">
            window
        </div>
        <div class="chat-box-emoj">
            emoj
        </div>
        <div class="chat-box-msg-box">
            <textarea id="msg"></textarea>
            <button class="btn btn-success">发送消息</button>
        </div>
    </div>
    <div class="clear-both"></div>
</div>

{% endblock %}

{% block bottom-js %}
<script>
//for csrf
// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');
console.log(csrftoken)

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}


//end csrf


    $(document).ready(function(){
        //set csrf before send ajax
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });
        //end set csrf

        //定时取消息
        /*var MsgRefresher = setInterval(function(){

            GetNewMsgs();
        },3000);
        */
        //end定时取沙

        GetNewMsgs();//开始去取消息


        $("#navbar a[href='{{ request.path }}']").parent().addClass("active");

        //send msg
        $("body").delegate("textarea", "keydown",function(e){
            if(e.which == 13) {//Enter key down
                //send msg button clicked
                var msg_text = $("textarea").val();
                if ($.trim(msg_text).length > 0){
                    console.log(msg_text);
                    SendMsg(msg_text);
                }
                //no wait the send_msg's call confirm msg
                AddSentMsgIntoBox(msg_text);
                $("textarea").val('');
            }
        });
    });//end doc ready
    function SendMsg(msg_text){
        var contact_type = $(".chat-box-title").attr("contact-type");
        var contact_id = $(".chat-box-title").attr("contact-id");
        if (contact_type && contact_id){
           var msg_item ={
                    'from': "{{ request.user.userprofile.id }}",
                    'to'  :contact_id,
                    'type':contact_type,
                    'msg' : msg_text
                }

            $.post("{% url 'send_msg' %}", {data:JSON.stringify(msg_item)},function(callback){

                console.log(callback);
            });//end post
        }//end if

    }
    function AddSentMsgIntoBox(msg_text){

        var new_msg_ele = "<div class='msg-item'>" +
                            "<span>" + "{{ request.user.userprofile.name }}"  + "</span>" +
                            "<span>"  + new Date().toLocaleTimeString() +"</span>" +
                            "<div class='msg-text'>" + msg_text +"</div>" +
                          "</div>"
        $(".chat-box-window").append(new_msg_ele);

        $('.chat-box-window').animate({
            scrollTop: $('.chat-box-window')[0].scrollHeight}, 500);

    }
    function OpenChatWindow(ele){
        console.log($(ele));

        $(ele).addClass("active");
        $(ele).siblings().removeClass("active");
        var contact_id = $(ele).attr("contact-id");
        var contact_name = $(ele).find(".contact-name").text();
        var contact_type = $(ele).attr("contact-type");

        var chat_box_title_content = "正在跟" +contact_name +"聊天";
        $(".chat-box-title").html(chat_box_title_content);
        $(".chat-box-title").attr("contact-id",contact_id);
        $(".chat-box-title").attr("contact-type",contact_type);
    }

    function GetNewMsgs(){
        console.log('-----getting new msgs-------');
        $.getJSON("{% url 'get_new_msgs' %}",function(callback){
            console.log(callback);

            GetNewMsgs();
        });//end post
    }


</script>
{% endblock %}